
import { getClassNames, Portal } from "magic-ui-react"
import { FC, useEffect, useImperativeHandle, useRef, useState } from "react"
import { CSSTransition } from "react-transition-group"
import { AppPortalPorpsType } from "./types"
import styles from './styles.module.less'
import { isFunction, isUndefined } from "lodash"
import './style.less';

const AppPortal: FC<AppPortalPorpsType> = (porps) => {

  const {
    defaultVisible = false,
    children,
    contentDefaultStyle = true,
    visible: visiblePorps,
    position,
    onClose,
    actionRef,
    bgBlur = false,
    bgMark = true,
    clickOtherClose = true,
    contentMobileAdaptation = true,
    unmountOnExit = true,
    classNames,
  } = porps

  const [visible, setVisible] = useState(defaultVisible);
  const nodeRef = useRef<HTMLDivElement>(null)

  useImperativeHandle(actionRef, () => ({
    open: () => {
      setVisible(true)
    },
    close: () => {
      setVisible(false)
    }
  }));

  return (
    <CSSTransition
      in={isUndefined(visiblePorps) ? visible : visiblePorps}
      timeout={{
        enter: 300,
        exit: 200,
      }}
      nodeRef={nodeRef}
      classNames={position}
      unmountOnExit={unmountOnExit}
    >
      <Portal visible={true}>
        <div
          className={getClassNames([
            styles.AppPortal,
            classNames,
            {
              [styles.AppPortalContentCenter]: position === 'center',
              ['appCompBgSm']: bgBlur,
              ['appNearBg']: bgMark,
              'pointer-events-none': !clickOtherClose
            }
          ])}
          onClick={(e) => {
            e.stopPropagation()
            if (clickOtherClose) {
              console.log('asdasd');

              setVisible(false)
              onClose?.()
            }
          }}
        >
          <div
            ref={nodeRef}
            onClick={(e) => {
              e.stopPropagation()
            }}
            className={getClassNames([
              styles.content,
              styles[`content-${position}`],
              {
                [styles.contentMobileAdaptation]: contentMobileAdaptation
              }
            ])}
          >
            <div
              className={getClassNames([
                {
                  [styles.contentDefaultStyle]: contentDefaultStyle
                }
              ])}
            >
              {isFunction(children) ? children(visible) : children}
            </div>
          </div>
        </div>
      </Portal>
    </CSSTransition>
  )
}

export default AppPortal